package com.pichub.psdmaster.filesDao.impl;

import com.pichub.psdmaster.Bean.FileInfo;
import com.pichub.psdmaster.ConnectDB;
import com.pichub.psdmaster.ConnectMainDB;
import com.pichub.psdmaster.filesDao.FileInfoDao;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class FileInfoDaoImpl implements FileInfoDao {
	private Connection conn = null;
	private PreparedStatement pstm = null;

	private Logger logger = Logger.getLogger("appender1");

	@Override
	public boolean Add(FileInfo fi) {
		ResultSet rs = null;
		String sql = "INSERT INTO t_file_info ( filename, md5, path, updatedate, author, filetype, filesize, width, height, avecolor) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
		try {
			conn = ConnectMainDB.getMainConnection();
			pstm = conn.prepareStatement(sql);

			pstm.setString(1, fi.getFileName());
			pstm.setString(2, fi.getMd5());
			pstm.setString(3, fi.getPath());
			pstm.setDate(4,new Date(System.currentTimeMillis()));
			pstm.setString(5,fi.getPath());
			pstm.setString(6, fi.getFiletype());
			pstm.setString(7, fi.getFilesize());

			pstm.setString(8, fi.getWidth());
			pstm.setString(9, fi.getHeight());
			pstm.setString(10, fi.getAvecolor());

			int re = pstm.executeUpdate();
			logger.info("pstm.executeUpdate()返回码为：" + re);
		} catch (SQLException e) {
			logger.error("pstm.executeUpdate()发生错误",e);
			return false;
		} finally {
			ConnectDB.free(rs, conn, pstm);
		}
		return true;
	}


	@Override
	public Long findIdByMD5(String md5){
		ResultSet rs = null;
		try {
			String sql="SELECT id from t_file_info where md5 =?";
			conn = ConnectMainDB.getMainConnection();
			pstm = conn.prepareStatement(sql);
			pstm.setString(1,md5);
			rs=pstm.executeQuery();
			if (rs.next()){
				return rs.getLong("id");
			}else {
				return null;
			}
		} catch (SQLException e) {
			logger.error("ERROR: ",e);
			return null;
		}finally {
			ConnectDB.free(rs, conn, pstm);
		}

	}

	@Override
	public boolean linkRelationShip(Long fid, Long pfid) {
		ResultSet rs = null;
		try {
			String sql="INSERT IGNORE INTO t_files_relation ( fid, pfid) VALUES ( ?, ?);";
			conn = ConnectMainDB.getMainConnection();
			pstm = conn.prepareStatement(sql);
			pstm.setLong(1,fid);
			pstm.setLong(2,pfid);
			int updaters=pstm.executeUpdate();
			if (updaters>0){
				return true;
			}else {
				return false;
			}
		} catch (SQLException e) {
			logger.error("ERROR: ",e);
			return false;
		}finally {
			ConnectDB.free(rs, conn, pstm);
		}
	}





}
